/*
 * @Author: jiu yin
 * @Date: 2025-01-07 16:54:32
 * @FilePath: \studio-web-admin\electron\node-socket-service\src\router\method.js
 * @LastEditTime: 2025-02-20 17:18:27
 * @LastEditors: jiu yin zhen jing
 */
const path = require("path");
const fs = require("fs");
const express = require("express");
const {rootPath}= require("../../utils.js");
let downloadPath = path.join(rootPath, "./downloads");

let method = {
	staticDownloads() {
		return express.static(downloadPath, {
			setHeaders: (res, filePath, stat) => {
				// 允许跨域
				res.set("Access-Control-Allow-Origin", "*");

				// 根据文件类型设置正确的 Content-Type
				if (filePath.endsWith(".apk")) {
					res.set("Content-Type", "application/vnd.android.package-archive");
				} else if (filePath.endsWith(".zip")) {
					res.set("Content-Type", "application/zip");
				}
				// 设置文件下载头
				const fileName = path.basename(filePath);
				res.set("Content-Disposition", `attachment; filename="${fileName}"`);
			},
			// 允许点击目录浏览文件
			dotfiles: "allow",
		});
	},
	downloads(req, res) {
		fs.readdir(downloadPath, (err, files) => {
			if (err) {
				console.error("读取目录失败:", err);
				return res.status(500).send("无法读取目录");
			}

			// 生成文件列表HTML
			const fileList = files
				.map(file => {
					const filePath = `/downloads/${file}`;
					return `<li><a href="${filePath}">${file}</a></li>`;
				})
				.join("");

			const html = `
                 <!DOCTYPE html>
                 <html>
                     <head>
                         <title>Downloads</title>
                         <meta charset="utf-8">
                         <style>
                             body { font-family: Arial, sans-serif; margin: 20px; }
                             ul { list-style-type: none; padding: 0; }
                             li { margin: 10px 0; }
                             a { color: #0066cc; text-decoration: none; }
                             a:hover { text-decoration: underline; }
                         </style>
                     </head>
                     <body>
                         <h1>本地文件目录</h1>
                         <ul>${fileList}</ul>
                     </body>
                 </html>
             `;

			res.send(html);
		});
	},
};
module.exports = method;
